<template>
    <div class="chatbox" @click="maxWrap">
		<!-- header -->
		<!-- <div style="height: .9rem;"></div> -->
		<div v-if="false" id="header">
			<div class="fav-head flex flex-space-x flex-center-y">
				<span class="fav-head-left" @click="goBack">
					<van-icon name="arrow-left" size="0.48rem" color="#fff" class="c-icon"/>
				</span>
				<span class="fav-head-title c-line-clamp1">联系客服</span>
				<div class="rightText"></div>
			</div>
			<div class="height"></div>
		</div>
		<!-- main -->
		<div class="chat-box"  :style="{...footerStyle, height: chatWindowsHeight}" ref="mainoverflow">
			<div class="chat" ref="main" @click.stop="show_emo = false,show_more = false">
				<!-- ********** 遍历 *********** -->
				<div class="item" v-for="(item,index) in formData" :key="item.msgId">
					<!-- 时间 -->
					<div class="time flex flex-center-x">
						<span>{{item.time | toDate}}</span>
					</div>
					<!-- 结算收图 -->
					<p class="remind" v-if="item.type == 'remindOver'">"{{item.fromName}}"提醒您 <span>结算收图</span></p>
					<!-- 改时间 -->
					<p class="remind" v-if="item.type == 'remindTime'">"{{item.fromName}}"提醒您 <span>修改时间</span></p>
					<!-- 上传图片 -->
					<p class="remind" v-if="item.type == 'remindUpload'">"{{item.fromName}}"提醒您 <span>上传图片</span></p>
					<!-- 提醒付款 -->
					<p class="remind" v-if="item.type == 'remindPay'">"{{item.fromName}}"提醒您 <span>付款</span></p>
					<!-- 确认 -->
					<p class="remind" v-if="item.type == 'remindConfirm'">"{{item.fromName}}"提醒您 <span>确认图片</span></p>
					<!-- 改图 -->
					<p class="remind" v-if="item.type == 'remindModif'">"{{item.fromName}}"提醒您 <span>改图</span></p>
					<!-- 人物头像 -->
					<div
						class="profile"
						:class="{self:userId==item.fromUser,other:userId!=item.fromUser}"
						v-if="item.type == 'text'
                        || item.type == 'txt'
                        ||item.type == 'image'
                        || item.type == 'video'
                        || item.type == 'map'
                        || item.type == 'voice'">
						<!-- 头像 -->
						<div class="pic" v-if="userId!=item.fromUser">
							<img :src="item.pic" @error="imgError(item)">
						</div>
						<!-- 内容 -->
						<div class="right">
							<div class="name">{{item.fromName}}</div>
							<!-- 纯文本 -->
							<div
								v-html="enter(item.payload)"
								class="msg"
								v-if="item.type == 'txt'"></div>
                            <!-- 语音 -->
                            <span v-if="item.type == 'voice'" class="voiceLength">{{item.length}}''</span>
                            <div
								@click="playVoice(item.payload,index)"
								class="msg"
								v-if="item.type == 'voice'"
								:style="{width:item.length<=10?'66px':'88px'}">
								<img src="@/assets/img/performance/msgCenter/chatPlay.png"
									style="width: 0.18rem;"
									v-if="!item.click"
									class="playImg">
								<img src="@/assets/img/performance/msgCenter/chatPlay.gif"
									style="width: 0.18rem;"
									v-if="item.click"
									class="playImg">
							</div>
							<!-- 表情兼文本 -->
							<div class="msg" v-if="item.type == 'text'"></div>
							<img :src="item.payload" v-else-if="item.type == 'image'" @click.stop="preview(item.payload)">
							<div class="coverPage" v-else-if="item.type == 'video'" @click.stop="toVideo(item.payload)">
								<img :src="item.coverPage" class="bgPic">
								<img src="@/assets/img/performance/msgCenter/playVideo.png" class="iconPlay">
							</div>
							<div class="map" v-else-if="item.type == 'map'" @click="toMap(item.payload)">
								<div class="title">
									<h3>{{item.title}}</h3>
									<p>{{item.address}}</p>
								</div>
								<position :DOM="`map${index}`" :position="item.payload"></position>
							</div>
						</div>
						<!-- 头像 -->
						<div class="pic" v-if="userId==item.fromUser">
							<img :src="item.pic" @error="imgError(item)">
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- 屁股 -->
		<form class="footer" :style="footerStyle" @submit.prevent="sendMsg('text',msg)">
            <div class="plus">
				<img src="@/assets/img/performance/msgCenter/emo.png"
					@click.stop="show_emo = !show_emo,
					show_more = false,
					messageSendType = 'emo',
					showVoice = false,
					updateChatWindowsHeight()">
                <img src="@/assets/img/performance/msgCenter/keyboard.png" @click.stop="showVoice = false" v-show="showVoice">
				<img src="@/assets/img/performance/msgCenter/voice.png"
					@click.stop="showVoice = true,show_emo = false,show_more = false"
					v-show="!showVoice">
				<img src="@/assets/img/performance/msgCenter/add.png"
					@click.stop="show_more = !show_more,
					show_emo = false,
					showVoice = false,
					updateChatWindowsHeight()">
			</div>
			<!-- 输入框 -->
			<div class="into flex flex-center-y" v-show="!showVoice">
				<textarea
                    type="text"
                    class="input"
                    v-model="msg"
                    ref="myInput"
                    @focus="inputFocus"
					@input="messageSendType = 'txt'"
                    @blur="inputBlur">
				</textarea>
				<div class="right" @click="sendMsg('text',msg)">发送</div>
			</div>
            <!-- 语音输入框 -->
			<div id="voice" style="margin-top: 1.2rem;" v-show="showVoice">
				<!-- 按钮 -->
				<div
					ref="footer"
					:class="{'press':speakText == '松开结束'}"
					class="btn"
					@touchstart.stop="speakStart"
					@touchmove.stop="speakMove"
					@touchend.stop="speakEnd">
					{{speakText}}
				</div>
			</div>
			<!-- 表情 -->
			<div class="emo" v-if="show_emo">
				<emoji @selectEmo="selectEmo" id="emoji"></emoji>
			</div>
			<!-- more -->
			<div class="more" v-if="show_more">
				<li @click="openImg()">
					<img src="@/assets/img/performance/msgCenter/img.png">
					<p>图片</p>
				</li>
			</div>
		</form>
        <!-- 录音动画 -->
        <div class="speak" v-show="showVoice2">
            <img src="@/assets/img/performance/msgCenter/icon_voice.gif">
            <p>{{speakText=='松开结束'?'正在录音':speakText}}</p>
        </div>
        <!-- 保存图片到本地 -->
		<download :showDown="showImages" :url="imgUrl"></download>
		<!-- 预览图片 -->
		<van-image-preview
			v-model="showImages"
			:images="images">
		</van-image-preview>
    </div>
</template>
<script>
import {formatDate} from '@/utils/date.js' //时间戳
import {inputAbsolute} from '@/utils/ios'
import apiConfig from '@/api/index'
import emoji from '@/components/performance/msgCenter/emoji/index' //emoji表情
import download from '@/components/performance/msgCenter/download' //下载图片
import voice from '@/components/performance/msgCenter/voice' //语音输入
import {getuserUid,getUserLogin,getUserInfo,getRole,getToken} from '@/utils/auth.js'
import {getHistory,setHistory,unique,toDate,getBase64Image,setHot,compressImage,toBase64} from '@/utils/chat.js'
import pushMsg from '@/utils/push.js'
import unread from '@/utils/unread.js'
import { Dialog } from 'vant';

function getChatWindowsHeight() {
	let _innerWidth = window.innerWidth / 7.5 * .6
	let title = window.innerWidth / 7.5 * 1.6
	let emHeight = 0
	// this.chatWindowsHeight = plus ? (plus.screen.resolutionHeight - title - 输入区域高度) + 'px' : '500px'
	console.log('this.messageSendType, this.show_emo')
	console.log(this.messageSendType, this.show_emo)
	// if(this.messageSendType === 'emo' && this.show_emo){
	// 	emHeight = window.innerWidth / 7.5 * 3
	// 	console.log('进来了~~~~~~~~~~~~')
	// }
	let chatWindowsHeight = (window.innerHeight - emHeight) + 'px'
	console.log('compute chatWindowsHeight')
	console.log(chatWindowsHeight)
	return  chatWindowsHeight
}

var WV_right = {
	id: 'right',
	tag: 'img',
	src: location.protocol === 'http:' ? 'http://192.168.0.111:8080/icon/profile.png' : './icon/profile.png',
	position: {top:'11px',right:'18px',width:'20px',height:'20px'},
	sprite: {top:'0px',left:'0px',width:'100%',height:'100%'}
}
var MV_back = {
	id: 'back',
	tag: 'img',
	src: location.protocol === 'http:' ? 'http://192.168.0.111:8080/back.png' : './back.png',
	position: {top:'11px',left:'18px',width:'10px',height:'18px'},
	sprite: {top:'0px',left:'0px',width:'100%',height:'100%'}
}
var MV_title = (name) => {
	return {tag:'font', id:'titlename', text: name, textStyles: { size: '18px', color: '#fff' }}
}

export default {
	components:{
		emoji,
        download,
        voice
	},
	watch: {
        msg(){
            //this.getHight();  //获取textarea的高度
        },
		title(v){
			this.isLoadTitle = true
			let titleName = `${v}`
			this.WV && this.WV.draw([ MV_title(titleName) ])
		},
		//滚动到最底部
		formData:function(x,y){
			if(this.pageCurrent == 1){
				setTimeout(()=>{
					this.scrollBottom();
				},500)
			}
		},
        minHeight(val){
            console.log('minHeight:' + this.minHeight);
        },
        showVoice(val){
            if(!val){
                this.$refs.myInput.focus();
            }
        },
	},
    data(){
		return{
			//msg
			formData:[
				// {
				// 	type:'text',
				// 	msgId:'599396448542394412',
				// 	time:1557122660953,
				// 	fromUser:'admin', //发送人id
				// 	fromName:'测试', //发送人name
				// 	pic:"",  //头像
				// 	payload:'你是谁', //聊天内容
				// },
				// {
				// 	type:"text",
				// 	msgId:'599396448542394413',
				// 	time:1557122660954,
				// 	fromUser:'834532c343a911e9855d6045cb8a6182', //发送人id
				// 	fromName:'吴彦祖', //发送人name
				// 	pic:"",  //头像
				// 	payload:'我是吴彦祖#大兵;', //聊天内容
				// },
				// {
				// 	type:"image",
				// 	msgId:'599396448542394414',
				// 	time:1557122660955,
				// 	fromUser:'834532c343a911e9855d6045cb8a6182', //发送人id
				// 	fromName:'吴彦祖', //发送人name
				// 	pic:"",  //头像
				// 	payload:'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1122649470,955539824&fm=27&gp=0.jpg;', //聊天内容
				// },
				// {
				// 	type:"image",
				// 	msgId:'5993964485423944122',
				// 	time:1557122660950,
				// 	fromUser:'629a8b00d027454d94684a07748e0067', //发送人id
				// 	fromName:'倪小明', //发送人name
				// 	pic:"",  //头像
				// 	payload:'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1122649470,955539824&fm=27&gp=0.jpg;', //聊天内容
				// },
				// {
				// 	type:"text",
				// 	msgId:'599396448542394413',
				// 	time:1557122660954,
				// 	fromUser:'834532c343a911e9855d6045cb8a6182', //发送人id
				// 	fromName:'吴彦祖', //发送人name
				// 	pic:"",  //头像
				// 	payload:'我是吴彦祖#大兵;', //聊天内容
				// },
				// {
				// 	type:"text",
				// 	msgId:'599396448542394413',
				// 	time:1557122660954,
				// 	fromUser:'834532c343a911e9855d6045cb8a6182', //发送人id
				// 	fromName:'吴彦祖', //发送人name
				// 	pic:"",  //头像
				// 	payload:'我是吴彦祖#大兵;', //聊天内容
				// },
			],

			//main
			msg:"",
			emoIndex:0, //用来判断是否纯文本,0表示没表情

			//footer
			show_emo:false,
			show_more:false,

			//预览图片
			showImages:false,
			images:[],
            imgUrl:"",

            //语音
            player:"",
            showVoice:false,  //是否显示语音，true为显示
            audioUrl:"",

			//other
			userId:"",
			roomId:"",
			once:true,

			//toast
			toast:"",

            //最小高度
			minHeight:"100vh",
			WV: null,
			footerStyle: {
				position: inputAbsolute() ? 'absolute' : 'fixed',
			},
			messageSendType: '',
			chatWindowsHeight: getChatWindowsHeight.bind(this)(),
			isLoadTitle: false,
			pageCurrent: 1,
			innerHeights: [],

            //按住讲话
            speakText:"按住说话",
            posStart:0,//初始化起点坐标
            posEnd:0,//初始化终点坐标
            posMove:0,//初始化滑动坐标
            voiceLen:0,  //语音时长
            timer:"", //定时器
            voiceTimer:"", //语音时间
            voiceStatus:true, //true才能提交
            voiceObj:"",  //录音对象
            showVoice2:false,
            voicePath:"", //录音完成后的地址（本地）
		}
	},
	methods:{
		//加载中
		loading:function(msg){
			const toast = this.$toast.loading({
				duration: 0,
				mask: false,
				message: msg,
				forbidClick:true
			});
			return toast;
		},
		//获取客服id
		list:function(){
			HTTP('advisory',{
				userUid:this.userId
			})
			.then(res=>{
				if(res.code == 200){
					console.log('聊天室id:' + res.data.roomId);
					this.roomId = res.data.roomId;
                    this.getRecord();
				}
				else{
					this.$toast(res.msg);
				}
			})
		},
        //开始录音
        speakStart:function(event){
            this.voiceStatus = true; //为true才能提交
            this.speakText = "松开结束";
            this.posStart = event.touches[0].pageY;
            this.showVoice2 = true; //显示悬浮物
            //获取时长
            this.voiceLen = 0;
            this.timer = setInterval(()=>{
                if(this.voiceLen >= 60){
                    this.speakEnd(); //结束录音
                }
                else{
                    this.voiceLen++;
                }
            },1000)
            //语音输入
            this.voiceObj = plus.audio.getRecorder();
            if(this.voiceObj == null){
                console.log('录音对象为空');
            }
            this.voiceObj.record( {
                filename:"_doc/audio/tuxiaozhu/",
                format:"mp3"
            }, (res)=> {
                //true才能上传
                if(this.voiceStatus){
                    console.log(res);
                    let obj = {
                        path:res,
                        time:this.voiceLen==0?1:this.voiceLen
                    };
                    this.uploadVoice(obj);
                }
            }, e=>{
                this.$toast('录音失败');
                console.log(e);
            });
        },
        //滑动时
        speakMove:function(event){
            this.posMove = 0;
            this.posMove = event.targetTouches[0].pageY;  //获取滑动实时坐标
            if(this.posStart - this.posMove < this.$refs.footer.clientHeight){
                console.log('松开结束');
                this.speakText = '松开结束';
                this.voiceStatus = true; //为true才能提交
            }
            else{
                console.log('取消发送');
                this.speakText = '取消发送';
                this.voiceStatus = false; //为true才能提交
            }
        },
        //结束录音
        speakEnd:function(event){
            console.log('手指松开...');
            clearInterval(this.timer);
            console.log('时长：' + this.voiceLen);
            //如果录音时间符合规范
            if(this.voiceLen<60){
                console.log('录音符合规范');
                this.posEnd = 0;
                this.posEnd = event.changedTouches[0].pageY; //获取终点坐标
                //发送成功
                if(this.posStart - this.posEnd < this.$refs.footer.clientHeight){
                    //提交
                    if(this.voiceStatus){
                        //结束录音
                        this.voiceObj.stop();
                        this.showVoice2 = false; //隐藏悬浮物
                        this.showSpeak = false;
                        this.voiceNum++;
                        this.speakText = '按住说话';
                        console.log('提交');
                    }
                }
                //取消发送
                else{
                    console.log('老子不发了');
                    this.voiceObj.stop(); //结束录音
                    this.showVoice2 = false; //隐藏悬浮物
                    this.speakText = '按住说话';
                }
            }
            //录音时间不符合规范
            else{
                //结束录音
                this.voiceObj.stop();
                this.showVoice2 = false; //隐藏悬浮物
                this.showSpeak = false;
                console.log('结束录音');
            }
        },
        //聊天记录
        getRecord:function(){
            HTTP('record',{
                pageNum:this.pageCurrent,
                pageSize:10,
                userUid:this.userId,
                groupUid:this.roomId,
                msgId:""
            })
            .then(res=>{
                if(res.code == 200){
                    console.log(res);
                    this.pageTotal = res.data.pages;
                    let local = getUserInfo();
                    console.log('改过头像:' + this.$store.state.modifProfile);
                    res.data.list.map(o=>{
                        let obj = JSON.parse(o.payload);
                        //预览图片数组
                        if(obj.ext.type == "image" || obj.ext.type == "works" || obj.ext.type == "editNone"){
                            let url = obj.bodies[0].url?obj.bodies[0].url:obj.ext.content;
                            this.images.unshift(url);
                        }
                        this.formData.unshift({
                            uid:obj.ext.uid?obj.ext.uid:'', //编辑图片才有
                            type:obj.ext.type, //类型
                            msgId:o.msgId, //消息id
                            time:parseInt(o.time), //发送时间
                            fromUser:o.fromUser, //发送人id
                            fromName:o.fromName, //发送人名字
                            //fromName:obj.ext.name, //发送人名字
                            pic:this.$store.state.modifProfile&&this.userId==o.fromUser?local.pictureUrl:obj.ext.photoUrl,  //头像
                            payload:obj.ext.content?obj.ext.content:obj.bodies[0].url,  //内容，不存在的就是视频（图片）
                            coverPage:obj.ext.type=='video'?obj.ext.coverPage:'',  //视频封面
                            title:obj.ext.title?obj.ext.title:'', //地图标题
                            address:obj.ext.address?obj.ext.address:'', //地图地址
                            length:obj.ext.length?obj.ext.length:'', //语音时长
                            click:false  //语音波纹
                        });
                    })
                    //滑到最底部
					this.imgLoad(this.images)
					.then(res=>{
						this.scrollBottom();
					})
                }
                else{
                    this.$toast(res.msg);
                }
            })
        },
		//失去焦点
		onBlur:function(){
			this.$refs.myInput.blur(); //失去焦点
		},
		//后退
		goBack:function(){
			console.log('失去焦点');
			this.$refs.myInput.blur()
			setTimeout(() => {
				this.$router.back();
			}, 300)
		},
		//整体区域点击
		maxWrap:function(e){
			//this.show_emo = false;
			this.show_more = false;
		},
		//选择表情
		selectEmo:function(i){
			this.msg = this.msg + i;
			this.messageSendType = 'emo'
		},
		//打开相册
		openImg:function(){
			plus.gallery.pick((path)=> {
				var _this = this;
				if(path){
					this.toast = this.loading('加载中');
					// 压缩图片
					compressImage(path)
					.then(res=>{
						// 转base64
						toBase64(res)
						.then(base64=>{
							this.sendImage(res,base64);
						})
					})
				}
			},
			{
				filter: "image"
			});
		},
		//失效图片处理
		imgError:function(item){
			item.pic = require('@/assets/img/performance/msgCenter/default.png');
		},
		//预览图片
		preview:function(img){
            this.imgUrl = img;  //传给子组件用的
            let index=0;
			let arrImg = [];
			//根据图片得到index
			this.images.map((o,n)=>{
				if(o == img){
					index = n;
				}
			})
			this.nImages = index;
			this.showImages = true;
		},
        //获取textarea高度
        getHight:function(){
            //控制最大高度100px
            if(this.$refs.myInput.scrollHeight<100){
                this.$refs.myInput.style.height = this.$refs.myInput.scrollHeight + 'px';
            }
            else{
                this.$refs.myInput.style.height = '100px';
            }
        },
        //播放声音
        playVoice:function(url,n){
            //新目标
			if(this.audioUrl != url){
				console.log('新目标');
				//把之前的暂停
				if(this.player){
					this.player.stop();
				}
				this.audioUrl = url;
				this.player = plus.audio.createPlayer(url);
				this.wave(n,true);  //开启波纹
				//播放结束的回调
				this.player.play(()=>{
					console.log('播放结束的回调');
					this.player = "";
					this.audioUrl = "";
					this.wave(n,false);  //关闭波纹
				});
			}
			else{
				//如果已经暂停/停止，让它播放
				if(this.player.isPaused()){
					console.log('如果已经暂停/停止，让它播放');
					this.audioUrl = url;
					this.player = plus.audio.createPlayer(url);
					this.wave(n,true);  //开启波纹
					//播放结束的回调
					this.player.play(()=>{
						console.log('播放结束的回调');
						this.player = "";
						this.audioUrl = "";
					});
				}
				//如果正在播放中，让它停止
				else{
					console.log('如果正在播放中，让它停止');
					this.player.stop();
					this.player = "";
					this.audioUrl = "";
					this.wave(n,false);  //关闭波纹
				}
			}
        },
        //开启/结束波纹
        wave:function(n,bol){
            console.log('波纹');
            //先关闭所有波纹
            if(bol){
                this.formData.map(o=>{
                    if(o.click){
                        o.click = false;
                    }
                })
            }
            //开启/关闭
            this.formData[n].click = bol;
        },
		//环信监听
		webIm:function(){
			this.$imconn.listen({
				//收到消息
				onTextMessage:(data)=>{
                    console.log(data);
					//自己发的不监听
                    if(data.from != this.userId){
                        if(data.type == 'chatroom'){
                            //文本消息
                            var timestamp = Date.parse(new Date()); //当前时间戳
                            this.formData.push({
                                type:data.ext.type, //text,image,video,remind,map
                                msgId:data.id, //消息id
                                time:timestamp,
                                fromUser:data.from, //发送人id
                                fromName:data.ext.name, //发送人名字
                                pic:data.ext.photoUrl,
                                payload:data.ext.content, //聊天内容
                                title:data.ext.title?data.ext.title:'', //地图消息，标题
                                address:data.ext.address?data.ext.address:''  //地图消息，地址
                            })
							//滑到最底部
							this.imgLoad(this.images)
							.then(res=>{
								this.scrollBottom();
							})
                        }
                        //如果是群组
                        else{
                            setHot(data.to); //开启红点
							unread(data.to);
                            pushMsg(data,'group');
                        }
                    }
				},
				//收到图片消息
				onPictureMessage:(data)=>{
					//如果是当前聊天室
                    if(data.type == 'chatroom'){
                        if(this.roomId == data.to && data.from != this.userId){
                            console.log(data);
                            var timestamp = Date.parse(new Date()); //当前时间戳
                            this.formData.push({
                                type:data.ext.type, //text or image?
                                msgId:data.id, //消息id
                                time:timestamp,
                                fromUser:data.from, //发送人id
                                fromName:data.ext.name, //发送人名字
                                pic:data.ext.photoUrl,
                                payload:data.url, //聊天内容
                            })
							//滑到最底部
							this.imgLoad(this.images)
							.then(res=>{
								this.scrollBottom();
							})
                        }
                    }
                    //如果是群组
                    else{
                        setHot(data.to); //开启红点
						unread(data.to);
                        pushMsg(data,'group');
                    }
				},
			})
		},
        //发送语音消息
        sendVoice:function(url,timeLen){
            console.log(url);  //已经上传好的url
            this.toast = this.loading('发送中');
            var obj = getUserInfo();
            var timestamp = Date.parse(new Date()); //当前时间戳
            var params = {
                title:this.title,
                orderId:this.$route.query.orderId,
                type:'voice',
                name:obj.userName,
                photoUrl:obj.pictureUrl,
                content:url,
                time:timestamp,
                length:timeLen,
				click:false,
                roleId:this.roleId  //PC用到
            };
            HTTP('msg',{
                roomType:'room',
                content:'语音',
                userUid:this.userId,
                groupUid:this.roomId,
                ext:JSON.stringify(params)
            })
            .then(res=>{
                if(res.code == 200){
                    console.log('发送成功');
                    this.toast.clear();
                    //拼到数组中
                    this.formData.push({
                        type:'voice',
                        time:timestamp,
                        fromUser:this.userId, //发送人
                        fromName:obj.userName?obj.userName:'', //发送人名字
                        pic:obj.pictureUrl,  //发送人头像
                        payload:url, //聊天内容
                        length:timeLen,
                        click:false
                    })
                }
                else{
                    this.$toast(res.msg);
                }
            })
        },
		//判断图片是否加载完成
		imgLoad:function(pics){
			return new Promise((resolve,reject)=>{
				const picsAll = pics.map((imgurl) => {
					return new Promise((resolve, reject) => {
						const img = new Image();
						img.src = imgurl;
						img.onload = () => resolve(imgurl);
						img.onerror = () => reject(new Error(imgurl + ' load error'));
					})
				});
				Promise.all(picsAll).then(() => {
					resolve('success');
				}).catch((e) => {
					reject('error');
				})
			})
		},
		//(类型,内容)
		sendMsg:function(type,content){
			if(this.messageSendType === 'txt'){
				this.$refs.myInput.focus(); //保持焦点
				if(mui.os.ios){
					this.footerStyle = {
						position: 'absolute'
					}
				}
			}
			if(content){
				if(content.length<150){
					//防止点多次
					if(this.once){
						this.once = false;
						//判断是否包含表情
						this.emoIndex = -1;
						let word = this.msg;
						let t = "";
						word.replace(/\#[\u4E00-\u9FA5]{1,3}\;/gi, this.ifEmo);
						//扩展字段
						var timestamp = Date.parse(new Date()); //当前时间戳
						var id = this.$imconn.getUniqueId();    // 生成本地消息id
						var msg = new WebIM.message('txt', id); // 创建文本消息
						var obj = getUserInfo();
						var params = {
							type:this.emoIndex>=0?'text':'txt',
							name:obj.userName,
							photoUrl:obj.pictureUrl,
							content:content,
							time:timestamp,
						    roleId:getRole()?getRole():''
						};
						//清空输入框
						if(type == 'text' || type == 'txt'){
							this.msg = '';
						}
						HTTP('msg',{
							roomType:'room',
							content:content,
							userUid:this.userId,
							groupUid:this.roomId,
							ext:JSON.stringify(params)
						})
						.then(res=>{
							if(res.code == 200){
								console.log('发送成功');
								this.once = true;
								//拼到数组中
								this.formData.push({
									type:this.emoIndex>=0?'text':'txt', //text or image?
									msgId:id, //消息id
									time:timestamp,
									fromUser:this.userId, //发送人
									fromName:obj.userName, //发送人名字
									pic:obj.pictureUrl,  //发送人头像
									payload:content, //聊天内容
								})
							}
							else{
								this.once = true;
								this.$toast(res.msg);
							}
						})
					}
				}
				else{
					this.$toast('字数不能大于150字符');
				}
			}
			else{
				this.$toast('请输入内容');
			}
		},
		//发送图片消息
		sendImage:function(path,baseUrl){
			this.toast = this.loading('发送中');
			var _this = this;
			var obj = getUserInfo();
			var timestamp = Date.parse(new Date()); //当前时间戳
			var ext = {
				title:this.title,
				orderId:this.$route.query.orderId,
				type:'image',
				name:obj.userName,
				photoUrl:obj.pictureUrl,
				time:timestamp,
                roleId:this.roleId  //PC用到
			};
			//开始上传
			HTTP('msgImg',{
				roomType:'room',
				base64file:baseUrl,
				userUid:this.userId,
				groupUid:this.roomId,
				ext:JSON.stringify(ext)
			})
			.then(res=>{
				if(res.code == 200){
                    this.toast.clear();
					//预览图片数组
					this.images.unshift(res.data.coverPage);
					//拼到数组中
					this.formData.push({
						type:'image',
						msgId:timestamp, //消息id
						time:timestamp,
						fromUser:_this.userId, //发送人
						fromName:obj.userName, //发送人名字
						pic:obj.pictureUrl,  //发送人头像
						payload:res.data.coverPage, //聊天内容res.data.coverPage
					})
				}
				else{
					this.$toast('图片上传失败');
				}
			})
		},
		//识别换行
		enter:function(str){
			let str1=str.replace(/\n/g,"<br/>")
			return str1
		},
        //上传录音文件
        uploadVoice:function(obj){
            this.toast = this.loading('加载中');
            let task = window.plus.uploader.createUpload(`${apiConfig.config.baseURL}photoEditor/photoUpload`,{
                method: 'POST',
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            },(data, status)=>{
                console.log(data);
                let res = (new Function("return " + data.responseText))();
                //上传完成
                if(res.code == 200){
                    console.log('录音的url地址：' + res.data);
                    this.sendVoice(res.data,obj.time); //上传完之后发送
                }
                else{
                    this.$toast(res.msg);
                }
            })
            task.setRequestHeader('token', getToken());
            task.addFile(obj.path, { key: 'file' }); //path为图片路径，key为后端给的字段名
            task.start(); //开始上传
        },
		//滚动条最底部
		scrollBottom:function(){
			let box = this.$refs.main
			if(!box){
				return
			}
			let run = () => {
				//第1页，滚动条在最底部
				if(this.pageCurrent == 1){
					box.scrollTop = box.scrollHeight + box.offsetHeight
				}
				//第N页
				else{
					box.scrollTop = box.scrollHeight + box.offsetHeight - this.mainHeight
				}
				this.mainHeight = box.scrollHeight
			}
			run()
			this.$nextTick(run)
		},
		//弹出客服
		dialogTimer:function(){
			if(this.$store.state.nDialog == 1){
				Dialog.alert({
					message: '客服的服务时间为9:00到18:00'
				}).then(() => {
					this.$store.commit("setDialog", 2);
				});
			}
		},
		inputFocus(){
			this.show_emo = false
			this.footer = true
			// if(mui.os.ios){
			// 	this.footerStyle = {
			// 		position: 'absolute'
			// 	}
			// }
			console.log('foucs')
			let iosShowInput = () => {
				// this.$refs.myInput.focus()
				// this.$refs.myInput.scrollIntoView()
				// this.$refs.myInput.scrollIntoView(false)

				// this.$refs.myInputBox.style.position = 'fixed'
				// this.$refs.myInputBox.style.bottom = '0'
				// this.$refs.myInputBox.style.position = 'absolute'
				this.updateChatWindowsHeight()
				this.scrollBottom()
			}
			;[50, 1e3].forEach(e => {
				setTimeout(iosShowInput, e)
			})
		},
		updateChatWindowsHeight(){
			// let run = () => {
				this.chatWindowsHeight = getChatWindowsHeight.bind(this)()
			// 	this.scrollBottom()
			// }
			// ;[0, 50, 100, 500].forEach(e => {
			// 	setTimeout(run, e)
			// })
		},
		inputBlur(){
			if(mui.os.ios){
				this.footerStyle = {
					position: inputAbsolute() ? 'absolute' : 'fixed',
				}
			}
			let func = () => {
				this.footer = false
				// this.updateChatWindowsHeight()
				let run = () => {
					this.chatWindowsHeight = '100%'
				}
				;[0, 50].forEach(e => {
					setTimeout(run, e)
				})
			}
			setTimeout(() => {
				// this.$refs.myInput.hasFocus()
				func()
			}, 500)
			func()
		},
		handleSize(){
			this.scrollBottom()
			this.innerHeights.push(window.innerHeight)
			this.innerHeights = this.innerHeights.filter( (item, index ,arr)=>arr.indexOf(item) === index )
			let maxValue = Math.max(...this.innerHeights)
			let minValue = Math.min(...this.innerHeights)
			let open = () => {
				console.log('键盘出来')
			}
			let close = () => {
				console.log('键盘关闭')
				// this.updateChatWindowsHeight()
				this.inputBlur()
			}
			if(this.innerHeights.length == 1){
				open()
				return
			}
			if(window.innerHeight === maxValue){
				close()
			}
			if(window.innerHeight === minValue){
				open()
			}
			this.showView = false
			setTimeout(() => {
				this.showView = true
			})
			console.log('-------------')
			console.log(this.innerHeights)
			console.log(window.innerHeight)
			console.log(maxValue, minValue)
		}
	},
	filters:{
		toDate:function(time){
			var date = new Date(time);
			return formatDate(date, 'yyyy-MM-dd hh:mm');
		}
	},
	mounted:function(){
		this.webIm(); //环信
		this.dialogTimer();  //客服服务时间
		if(window.plus){
			let CWV = plus.webview.currentWebview()
			let runListenText = false

			CWV.setStyle({
				// kernel: 'UIWebview',
				// height: window.inn,
				softinputMode: "adjustResize",
				// softinputNavBar: 'none'
			})
		}
		window.addEventListener('resize', this.handleSize.bind(this), false)
	},
	created:function(){
			this.once = true;
			this.WV = new plus.nativeObj.View(
				'chat',
				{
					top: '0px',
					left: '0px',
					height: '44px',
					width: '100%',
					backgroundColor: '#5E8EFE',
					color: '#ffff',
				},
				[MV_back, MV_title('联系客服')]
			)
			this.WV.show()
			this.WV.addEventListener('click', (e) => {
				let lr
				if(e.clientX < (window.innerWidth / 4)){
					lr = 'left'
				}
				if(e.clientX > (window.innerWidth / 4 * 3)){
					lr = 'right'
				}
				// console.log(e, lr)
				if(lr === 'right'){
					// this.toDetail()
					return
				}
				if(lr === 'left'){
					this.goBack()
					return
				}
			})
		//获取userId
		if(getuserUid()){
			this.userId = getuserUid();
			this.list(); //获取聊天室id
		}
	},
	destroyed(){
		window.removeEventListener('resize', this.handleSize, false)
		let run = () => {
			this.WV && this.WV.hide()
			plus.webview.currentWebview().setStyle({
				softinputMode: "adjustPan"
			})
		}
		;[0, 50, 100, 1001].forEach(e => {
			setTimeout(run, e)
		})
	}
};
</script>

<style lang="scss" scoped>
.chatbox{
	.list-more{
		text-align: center;
		color: $color-primary;
		padding: 15px 0 10px 0;
	}
	//header
	.header{
		position: relative;
		z-index: 2001;
		.icon{
			//width: .4rem;
		}
		.height{
			height: .9rem;
		}
		.fav-head {
			position: absolute;
			top: 0;
			left: 0;
			z-index: 500;
			width: 100%;
			height: .92rem;
			background-color: #5E8EFE;
			color: #fff;
			-webkit-transform: translate3d(0, 0, 0);
			transform: translate3d(0, 0, 0);
		}
		.theme-dark {
			background-color: rgb(40,40,40);
			color: #fff;
		}
		.fav-head-left {
			margin-left: .22rem;
		}
		.rightText{
			margin-right: .22rem;
			font-size: .32rem;
		}
		.c-icon {
			font-size: .37rem;
		}
		.c-line-clamp1 {
			display: block;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			font-size: .35rem;
		}
	}
	.chat-box{
		position: relative;
		height: 100vh;
		width: 100%;
		-webkit-overflow-scrolling: touch;
		overflow: auto;
		padding-top: 44px;
		padding-bottom: 1.8rem;
		box-sizing: border-box;
		// background-color: #00f;
		bottom: 0px;
	}
	//主体
	.chat{
		// position: fixed;
		// top: 0px;
		// left: 0px;
		// right: 0px;
		overflow-y: auto;
		width: 94%;
		margin: 0 auto;
		// padding-bottom: 1.8rem;
		// height: calc(100vh - 10rem);
		// height: 700px;
		// background-color: red;
		// max-height: calc(100vh - .9rem);
		height: 100%;
		// height: calc(100vh - 2.6rem);
		// padding-bottom: .4rem;
		-webkit-overflow-scrolling: touch;
		.item{
			margin: 10px 0 4px 0;
			//时间
			.time{
				span{
					display: inline-block;
					padding: 4px 6px;
					color: #fff;
					border-radius: 3px;
					background-color: #dcdcdc;
				}
			}
			//提醒结算
			.remind{
				color: #555;
				padding: 15px 0;
				text-align: center;
				span{
					color: $color-primary;
				}
			}
			//人物头像
			.profile{
				display: flex;
				margin: 0.3rem 0;
				.pic{
					width: 0.8rem;
					height: 0.8rem;
					overflow: hidden;
					img{
						width: 100%;
						height: 100%;
					}
				}
				.right{
					display: block;
					width: calc(100% - 1rem);
					img{
						width: 50%;
						//min-height: 2rem;
					}
					//来自作品中心
					.works{
						width: 70%;
						.img{
							width: 70%;
							//min-height: 2rem;
						}
						p{
							display: inline-block;
							padding: 4px 10px;
							margin-top: 2px;
							background-color: #C5C5C5;
							color: #fff;
							border-radius: 6px;
						}
					}
				}
				.name{
					color: #999;
					margin: -4px 0 2px 0;
				}
				.msg{
					word-break:break-word;
					position: relative;
					padding: 0.18rem;
					box-sizing: border-box;
					border-radius: 4px;
					font-size: $fz-4;
					max-width: calc(100% - 1rem);
					min-width: 40px;
				}
			}
			//别人
			.other{
				.name{
					text-align: left;
				}
				.voiceLength{
					display: inline-block;
					color: #666;
					padding: 0 6px;
					margin-top: .15rem;
				}
				.msg{
					float: left;
					text-align: left;
					background-color: #fff;
					.playImg{
						display: block;
					}
				}
				.msg:before{
					content:" ";
					position: absolute;
					top: 12px;
					right: 100%;
					border:6px solid transparent;
					border-right-color:#fff;
				}
				.right{
					margin-left: 10px;
					text-align: left;
				}
				.coverPage{
					position: relative;
					width: 3rem;
					height: 2.5rem;
					background-color: #ccc;
					overflow: hidden;
					.bgPic{
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
					}
					.iconPlay{
						width: 1rem;
						height: 1rem;
						position: absolute;
						top: 50%;
						left: 50%;
						margin-top: -0.5rem;
						margin-left: -0.5rem;
						opacity: 0.9;
					}
				}
			}
			//自己
			.self{
				justify-content: flex-end;
				.works{
					float: right;
				}
				.name{
					text-align: right;
				}
				.voiceLength{
					display: inline-block;
					color: #666;
					padding: 0 6px;
					margin-top: .15rem;
				}
				.msg{
					text-align: left;
					float: right;
					background-color: #b2e281;
					.playImg{
						display: block;
						float: right;
						transform:rotate(180deg);
					}
				}
				.msg:before{
					content:" ";
					position: absolute;
					top: 12px;
					right: -12px;
					border:6px solid transparent;
					border-left-color:#b2e281;
				}
				.coverPage{
					float: right;
					position: relative;
					width: 3rem;
					height: 2.5rem;
					background-color: #ccc;
					overflow: hidden;
					.bgPic{
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
					}
					.iconPlay{
						width: 1rem;
						height: 1rem;
						position: absolute;
						top: 50%;
						left: 50%;
						margin-top: -0.5rem;
						margin-left: -0.5rem;
						opacity: 0.9;
					}
				}
				.map{
					float: right;
				}
				.right{
					margin-right: 10px;
					text-align: right;
				}
			}
		}
	}
	//屁股
	.footer{
		z-index: 200;
		left: 0;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
		background-color: #F1F1F1;
		// background-color: #0ff;
		justify-content: space-between;
		box-shadow:$box-shadow-light-1;
		overflow: hidden;
		.plus{
			padding: 0.2rem 0 0 0.3rem;
			img{
				width: 0.4rem;
				margin-right: 0.2rem;
			}
		}
		//输入框
		.into{
			padding: 0.2rem;
			.input{
				width: calc(100% - 1rem);
				margin-left: .1rem;
				border: none;
				height: .6rem;
				line-height: .6rem;
                //padding-right: 4px;
				padding: 4px;
				padding-left: 10px;
				color: #666;
				font-size: $fz-4;
				border-radius: 3px;
			}
			.right{
				width: 1rem;
				text-align: center;
				color: $color-primary;
				font-size: $fz-4;
				margin-left: 0.1rem;
			}
		}
		//表情
		.emo{
			padding: 0.2rem;
			border-top: 1px solid $border-color-base;
			#emoji{
				width: 100%;
				height: 3.16rem;
				background: #F1F1F1;
				overflow: hidden;
			}
		}
		//more
		.more{
			padding: 0.2rem;
			border-top: 1px solid $border-color-base;
			display: flex;
			flex-wrap: wrap;
			height: 3.8rem;
			li{
				width: 25%;
				text-align: center;
				list-style:none;
				margin: .13rem 0;
				img{
					width: 60%;
				}
				p{
					color: #666;
					padding-top: 4px;
				}
			}
		}
	}
	//@功能
	.at{
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		ul{
            margin-top: 1rem;
			li{
				display: flex;
				position: relative;
				padding: 10px;
				.pic{
					width: 0.8rem;
					height: 0.8rem;
					overflow: hidden;
					img{
						width: 100%;
						height: 100%;
					}
				}
				.name{
					height: 0.8rem;
					line-height: 0.8rem;
					padding-left: 10px;
					font-size: $fz-5;
				}
			}
			li:after{
				content: "";
				position: absolute;
				left: calc(0.8rem + 20px);
				right: 0;
				bottom: 0;
				bottom: 0;
				border-bottom: 1px solid $border-color-base;
			}
		}
	}
	//地图
	.map{
		width: 5rem;
		.title{
			width: 100%;
			background-color: #fff;
			padding: 6px 0;
			h3{
				width: 95%;
				margin: 0 auto;
				padding-bottom: 2px;
				font-weight: normal;
				word-wrap: normal;
				text-overflow: ellipsis;
				white-space: nowrap;
				overflow: hidden;
			}
			p{
				width: 95%;
				margin: 0 auto;
				color: #666;
				word-wrap: normal;
				text-overflow: ellipsis;
				white-space: nowrap;
				overflow: hidden;
			}
		}
	}
    #voice{
    .btn{
            position: fixed;
            bottom: 0;
            width: 100%;
            height: 1.1rem;
            line-height: 1.1rem;
            //height: 50px;
            //line-height: 50px;
            text-align: center;
            background-color: #fff;
        }
        //按住的状态
        .press{
            background-color: #F5F5F5;
        }
    }

    //显示录音图标
    .speak{
        position: fixed;
        left: 50%;
        bottom: 4rem;
        margin-left: -1rem;
        color: #fff;
        width: 2rem;
        background-color: #252525;
        opacity: 0.8;
        text-align: center;
        border-radius: 6px;
        padding: 0.3rem 0;
        z-index: 500;
        img{
            width: 50%;
        }
        p{
            padding-top: 10px;
        }
    }
}
</style>
